package edu.mtu.citizenscience.cs.utils.services;

import android.app.Service;
import android.os.Handler;
/**
 * @author Corbin Uselton <corbinu@cwuselto@mtu.edu>
 * @copyright (c) 2012 MichiganTech <http://www.mtu.edu>
 * @since 1.0
 * 
 * Handler for stopping a service after a set amount of time
 * used to run a service in the background of an app since
 * there is no onStop for the app class in android
 */
public class StopHandler extends Handler {
	// the service to stop
	private Service service;
	// whether the stop timer is running or not
	private boolean running = false;
	
	// run after the timer ends
	private Runnable runnableStop = new Runnable() 
	{
		@Override
	    public void run() 
		{
			// stop the service
	        service.stopSelf();
	    }
	};
	
	/**
	 * Create a new stop handler
	 * 
	 * @param   service - Service - the service to stop
	 * @return	void
	 */
	public StopHandler(Service service)
	{
		// set the handlers service
		this.service = service;
	}
	
	/**
	 * Start the stop counter for a number of seconds
	 * 
	 * @param   seconds - int - the seconds before the service stops
	 * @return	void
	 */
	public void stopIn(int seconds)
	{
		// if the handler timer is not already running
		if ( ! this.running)
		{
			// the timer is now running
			this.running = true;
			// run runnableStop in the passed number of secounds
			this.postDelayed(runnableStop, seconds * 1000);
		}
	}
	
	/**
	 * Cancel the stop counter
	 * 
	 * @param   void
	 * @return	void
	 */
	public void cancel()
	{
		// remove the delayed callback
		this.removeCallbacks(runnableStop);
		// the timer is no longer running
		this.running = false;
	}

}
